package com.dl.chat.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Set;

@Service
public class RedisService {

    private static final Logger log = LoggerFactory.getLogger(RedisService.class);
    @Autowired
    private RedisTemplate<String, Map<String,String>> redisTemplate;

    // 保存对话历史到 Redis
    public void saveChatHistory(String userId, List<Map<String, String>> history) {
        String key = "chat:history:" + userId;
        redisTemplate.opsForList().rightPushAll(key, history);
    }


    //获取所有用户ID
    public List<String> getAllUserIds() {
        String pattern = "chat:history:*";
        Set<String> keys = redisTemplate.keys(pattern);
        return keys.stream().map(key -> key.replace("chat:history:", "")).toList();
    }

    //从Redis获取对话历史
    public List<Map<String, String>> getChatHistory(String userId) {
        log.info("从Redis获取对话历史：{}",userId);
        String key = "chat:history:" + userId;
        List<Map<String, String>> range = redisTemplate.opsForList().range(key, 0, -1);
        return range;
    }


    // 清空对话历史
    public void clearChatHistory(String userId) {
        String key = "chat:history:" + userId;
        redisTemplate.delete(key);
    }
}
